package common.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.security.KeyStore;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import javax.net.ssl.SSLContext;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import staticclass.CommonConfig;

import weibo4j.model.PostParameter;

import common.impl.exception.ServiceException;

public class MicroBlog {

	public static String get(String url, PostParameter[] params) {

		if (null != params && params.length > 0) {
			String paramsStr = parameters(params);
			if (-1 == url.indexOf("?")) {
				url += "?" + paramsStr;
			} else {
				url += "&" + paramsStr;
			}
		}

		GetMethod getMethod = new GetMethod(url);
		getMethod.getParams().setContentCharset("utf-8");
		getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
				new DefaultHttpMethodRetryHandler());
		HttpClient httpClient = new HttpClient();
		try {
			int statusCode = httpClient.executeMethod(getMethod);
			if (statusCode != HttpStatus.SC_OK) {
				throw new ServiceException("ERR-");
			}
			String s = getMethod.getResponseBodyAsString();
			return s;
		} catch (Exception e) {
			// throw new ServiceException("ERR-");
			return "{\"ret\":1}";
		} finally {
			getMethod.releaseConnection();
		}
	}

	/**
	 * 签名
	 * 
	 * @param params
	 * @param signKey
	 * @return
	 */
	public static String sign(Map<String, String> params, String signKey) {
		List<String> keys = new ArrayList<String>(params.keySet());
		Collections.sort(keys);
		String prestr = "";
		for (int i = 0; i < keys.size(); i++) {
			String key = keys.get(i);
			String value = params.get(key);
			if (i == keys.size() - 1) {// 拼接时，不包括最后一个&字符
				prestr = prestr + key + "=" + value;
			} else {
				prestr = prestr + key + "=" + value + "&";
			}
		}
		try {
			prestr += "&key=" + signKey;
			byte[] buff = prestr.getBytes("utf-8");
			String sign = DigestUtils.md5Hex(buff).toUpperCase();
			return sign;
		} catch (Exception e) {
		}
		return null;
	}
	
	public static String post(String url, PostParameter[] params) {
		PostMethod postMethod = new PostMethod(url);
		if (null != params)
			for (int i = 0; i < params.length; i++) {
				if (!StringUtils.isEmpty(params[i].getValue()))
					postMethod.addParameter(params[i].getName(), params[i]
							.getValue());
			}
		HttpMethodParams param = postMethod.getParams();
		param.setContentCharset("UTF-8");

		postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
				new DefaultHttpMethodRetryHandler());

		HttpClient httpClient = new HttpClient();
		try {
			httpClient.executeMethod(postMethod);

			String s = postMethod.getResponseBodyAsString();
			return s;
		} catch (Exception e) {
			return e.getMessage();
		} finally {
			postMethod.releaseConnection();
		}
	}

	/**
	 * post请求
	 * @param url
	 * @param inputStr
	 * @param params
	 * @return
	 */
	public static String post(String url, String inputStr,
			PostParameter[] params) {
		String text = "";
		CloseableHttpClient httpclient = null;
		CloseableHttpResponse response = null;
		try {
			httpclient = HttpClients.custom().build();
			// 判断是否有search参数
			if (null != params) {
				int i1 = url.indexOf("?");
				for (int i = 0; i < params.length; i++) {
					if (i1 >= -1)
						url += "&";
					else
						url += "?";
					url += params[i].getName() + "=" + params[i].getValue();
				}
			}
			HttpPost httpPost = new HttpPost(url);
			// 判断是否有post数据
			if (!StringUtils.isEmpty(inputStr)) {
				StringEntity se = new StringEntity(inputStr, HTTP.UTF_8);
				httpPost.setEntity(se);
			}
			// 执行请求
			response = httpclient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			text = EntityUtils.toString(entity, "UTF-8");
			EntityUtils.consume(entity);
		} catch (Exception e) {
			text = e.getMessage();
		} finally {
			if (null != httpclient)
				try {
					httpclient.close();
				} catch (Exception e2) {
				}
			if (null != response)
				try {
					response.close();
				} catch (Exception e2) {
				}
		}
		return text;
	}
	
	/**
	 * https post请求
	 * 
	 * @param url
	 * @param inputStr
	 *            post数据
	 * @param certFile
	 *            证书文件相对路径，不带“/”
	 * @param certPass
	 *            证书文件密码
	 * @return
	 */
	public static String postHttps(String url, String inputStr,
			String certFile, String certPass) {
		String text = "";
		CloseableHttpClient httpclient = null;
		CloseableHttpResponse response = null;
		FileInputStream instream = null;
		try {
			// 是否有证书文件和密码
			if (!StringUtils.isEmpty(certFile)
					&& !StringUtils.isEmpty(certPass)) {
				KeyStore keyStore = KeyStore.getInstance("PKCS12");
				instream = new FileInputStream(new File(CommonConfig.realPath
						+ certFile));
				keyStore.load(instream, certPass.toCharArray());
				SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(
						keyStore, certPass.toCharArray()).build();
				SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
						sslcontext,
						new String[] { "TLSv1" },
						null,
						SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
				httpclient = HttpClients.custom().setSSLSocketFactory(sslsf)
						.build();
			} else {
				httpclient = HttpClients.custom().build();
			}
			HttpPost httpPost = new HttpPost(url);
			// 判断是否有post数据
			if (!StringUtils.isEmpty(inputStr)) {
				StringEntity se = new StringEntity(inputStr, HTTP.UTF_8);
				httpPost.setEntity(se);
			}
			// 执行请求
			response = httpclient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			text = EntityUtils.toString(entity, "UTF-8");
			EntityUtils.consume(entity);
		} catch (Exception e) {
			text = e.getMessage();
		} finally {
			if (null != instream)
				try {
					instream.close();
				} catch (Exception e2) {
				}
			if (null != httpclient)
				try {
					httpclient.close();
				} catch (Exception e2) {
				}
			if (null != response)
				try {
					response.close();
				} catch (Exception e2) {
				}
		}
		return text;
	}
	
	public static String parameters(PostParameter[] postParams) {
		StringBuffer buf = new StringBuffer();
		for (int j = 0; j < postParams.length; j++) {
			if (j != 0) {
				buf.append("&");
			}
			buf.append(postParams[j].getName()).append("=").append(
					postParams[j].getValue());
		}
		return buf.toString();
	}

}
